package com.xinyue.game.server.codec;

import com.xinyue.game.server.codec.message.IGameMessage;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;

public class EncodeHandler extends ChannelOutboundHandlerAdapter {

	@Override
	public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
		IGameMessage gameMessage = (IGameMessage) msg;
		int messageSize = GameMessageHeader.HEADER_LENGHT;
		GameMessageHeader header = gameMessage.getHeader();
		byte[] body = gameMessage.getBody();
		if (body != null && body.length > 0) {
			// TODO 将来添加消息加密和压缩
			messageSize += body.length;
		}
		ByteBuf byteBuf = ctx.alloc().buffer(messageSize);
		byteBuf.writeInt(messageSize);
		header.write(byteBuf);
		byteBuf.writeBytes(body);
		ctx.writeAndFlush(byteBuf, promise);
	}
}
